<?php 
    //设备端发起三位验证登录，后台返回三位验证码
    $sn = $_GET['device'];
    if ($sn == '') {
        $return_data = array('status'=>2,'data'=>'');
    }else{
        $pdo = new PDO('mysql:host=123.57.16.97;dbname=device_binding','root','zqVnUy6cxsQXbpEZ');
        $pdo->exec('set names utf8');
        $random = checkRandomRepeat($pdo);
        if (!$random) {
            $random = checkRandomRepeat($pdo);
        }
        $time = time();
        $sql = "INSERT INTO interim(random,device_sn,found_time) VALUES('$random','$sn','$time')";
        $res = $pdo->exec($sql);
        if ($res) {
            $return_data = array('status'=>1,'data'=>$random);
        }else{
            $return_data = array('status'=>0,'data'=>'获取验证码失败，请重试');
        }
    }
    echo json_encode($return_data);
    
    //验证随机数是否已经存在
    function checkRandomRepeat($pdo){
        $random = getRandom();
        $sql = "SELECT * FROM interim WHERE random = '$random'";
        $random_data = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
        if ($random_data) { 
            checkRandomRepeat($pdo);
        }else{
            return $random;
        }
    }

    //获取随机数
    function getRandom(){
        $random = mt_rand(100,999);
        if ($random) {
            return $random;    
        }else{
            getRandom();
        }
    }
 ?>